#!/usr/bin/env ts-node
/**
 * Phase间门控验证脚本
 * 用于验证Phase间数据流对齐和质量门控
 */

import * as fs from 'fs';
import * as path from 'path';
import { exec } from 'child_process';
import { promisify } from 'util';

const execAsync = promisify(exec);

const getErrorMessage = (error: unknown): string => {
  if (error instanceof Error) {
    return error.message;
  }
  if (typeof error === 'string') {
    return error;
  }
  try {
    return JSON.stringify(error);
  } catch {
    return String(error);
  }
};

interface ValidationResult {
  phase: string;
  gate: string;
  passed: boolean;
  errors: string[];
  warnings: string[];
  score?: number;
}

interface ContractProps {
  [key: string]: {
    type: string;
    default?: any;
    source?: string;
    derivedFrom?: string[];
  };
}

interface RequirementField {
  type: string;
  source: string;
  required: boolean;
  default?: any;
}

class PhaseGateValidator {
  private componentName: string;
  private workflowRoot: string;

  constructor(componentName: string) {
    this.componentName = componentName;
    this.workflowRoot = path.join(process.cwd(), 'Workflow/FigmaMCPWorkflow');
  }

  /**
   * Phase2到Phase3的验证门控
   */
  async validatePhase2to3(): Promise<ValidationResult> {
    const result: ValidationResult = {
      phase: 'Phase2-3',
      gate: 'Props Contract Validation',
      passed: true,
      errors: [],
      warnings: []
    };

    try {
      // 读取Props契约
      const contractPath = path.join(this.componentName, 'phase2/props-contract.json');
      if (!fs.existsSync(contractPath)) {
        result.errors.push(`Props contract not found: ${contractPath}`);
        result.passed = false;
        return result;
      }

      const contract = JSON.parse(fs.readFileSync(contractPath, 'utf-8'));
      const propCount = Object.keys(contract.props || {}).length;
      if (propCount === 0) {
        result.errors.push('Props contract has no props defined');
        result.passed = false;
      }

      // 验证数据转换器
      if (contract.transformers) {
        for (const transformer in contract.transformers) {
          const transformerDef = contract.transformers[transformer];
          if (transformerDef.location === 'Preview component') {
            // 检查Preview组件是否实现转换
            const previewPath = path.join(
              'src/components/editor/schema/preview/components',
              this.componentName,
              'index.tsx'
            );

            if (fs.existsSync(previewPath)) {
              const previewContent = fs.readFileSync(previewPath, 'utf-8');
              if (!previewContent.includes(transformer)) {
                result.warnings.push(`Transformer ${transformer} may not be implemented in Preview`);
              }
            }
          }
        }
      }

      // 计算覆盖率分数
      result.score = propCount;

    } catch (error) {
      result.errors.push(`Validation error: ${getErrorMessage(error)}`);
      result.passed = false;
    }

    return result;
  }

  /**
   * Phase3到Phase4的验证门控
   */
  async validatePhase3to4(): Promise<ValidationResult> {
    const result: ValidationResult = {
      phase: 'Phase3-4',
      gate: 'Panel Coverage Validation',
      passed: true,
      errors: [],
      warnings: []
    };

    try {
      // 读取面板分析结果
      const analysisPath = path.join(this.componentName, 'phase3/panel-reuse-analysis.json');
      if (!fs.existsSync(analysisPath)) {
        result.errors.push(`Panel analysis not found: ${analysisPath}`);
        result.passed = false;
        return result;
      }

      const analysis = JSON.parse(fs.readFileSync(analysisPath, 'utf-8'));

      // 如果不需要自定义面板，验证通过
      if (!analysis.needsCustomPanel) {
        result.warnings.push('Phase4 will be skipped - all fields covered by existing panels');
        return result;
      }

      // 验证自定义面板规格
      const customPanels = analysis.customPanelRequirements || [];
      if (customPanels.length === 0) {
        result.errors.push('needsCustomPanel=true but no custom panels specified');
        result.passed = false;
        return result;
      }

      // 检查每个自定义面板的字段定义
      for (const panel of customPanels) {
        if (!panel.fields || panel.fields.length === 0) {
          result.errors.push(`Panel ${panel.panelName} has no fields defined`);
          result.passed = false;
        }

        if (!panel.belongTo) {
          result.errors.push(`Panel ${panel.panelName} missing belongTo property`);
          result.passed = false;
        }
      }

      // 验证面板复用率
      if (analysis.statistics && analysis.statistics.reuseRate < 0.7) {
        result.warnings.push(`Low panel reuse rate: ${analysis.statistics.reuseRate}`);
      }

      result.score = Math.round((analysis.statistics?.reuseRate || 0) * 100);

    } catch (error) {
      result.errors.push(`Validation error: ${getErrorMessage(error)}`);
      result.passed = false;
    }

    return result;
  }

  /**
   * Phase4到Phase5的验证门控
   */
  async validatePhase4to5(): Promise<ValidationResult> {
    const result: ValidationResult = {
      phase: 'Phase4-5',
      gate: 'Implementation Completeness',
      passed: true,
      errors: [],
      warnings: []
    };

    try {
      // 检查Phase4执行决策
      const decisionPath = path.join(this.componentName, 'phase4/execution-decision.json');
      if (!fs.existsSync(decisionPath)) {
        result.errors.push(`Phase4 execution decision not found: ${decisionPath}`);
        result.passed = false;
        return result;
      }

      const decision = JSON.parse(fs.readFileSync(decisionPath, 'utf-8'));

      if (decision.executed) {
        // 验证自定义面板实现
        const reportPath = path.join(this.componentName, 'phase4/execution-report.json');
        if (!fs.existsSync(reportPath)) {
          result.errors.push('Phase4 executed but no report found');
          result.passed = false;
          return result;
        }

        const report = JSON.parse(fs.readFileSync(reportPath, 'utf-8'));

        // 验证面板覆盖率
        if (report.fieldCoverage && report.fieldCoverage.rate < 0.95) {
          result.errors.push(`Insufficient field coverage: ${report.fieldCoverage.rate}`);
          result.passed = false;
        }

        // 验证注册完整性
        const registration = report.registration || {};
        const requiredRegistrations = ['headerMap', 'initEditFields', 'filterArrays', 'renderConditions', 'defaultExpanded'];

        for (const reg of requiredRegistrations) {
          if (!registration[reg]) {
            result.errors.push(`Missing registration: ${reg}`);
            result.passed = false;
          }
        }

        result.score = Math.round(report.fieldCoverage?.rate * 100 || 0);
      } else {
        result.warnings.push(`Phase4 skipped: ${decision.reason}`);
        result.score = 100; // 跳过Phase4不影响分数
      }

    } catch (error) {
      result.errors.push(`Validation error: ${getErrorMessage(error)}`);
      result.passed = false;
    }

    return result;
  }

  /**
   * 验证requirement字段覆盖
   */
  async validateRequirementCoverage(): Promise<ValidationResult> {
    const result: ValidationResult = {
      phase: 'Requirements',
      gate: 'Requirement Fields Coverage',
      passed: true,
      errors: [],
      warnings: []
    };

    try {
      // 读取requirement字段
      const requirementPath = path.join(this.componentName, 'phase0/requirement-fields.json');
      if (!fs.existsSync(requirementPath)) {
        result.warnings.push('No requirement-fields.json found, skipping validation');
        return result;
      }

      const requirements = JSON.parse(fs.readFileSync(requirementPath, 'utf-8'));
      const requiredFields = Object.keys(requirements.fields || {});

      // 读取Props契约
      const contractPath = path.join(this.componentName, 'phase2/props-contract.json');
      if (!fs.existsSync(contractPath)) {
        result.errors.push('Props contract not found');
        result.passed = false;
        return result;
      }

      const contract = JSON.parse(fs.readFileSync(contractPath, 'utf-8'));

      // 检查所有必需字段的映射
      const missingMappings: string[] = [];
      for (const field of requiredFields) {
        const mapping = contract.requirementAlignment?.mappings?.[field];
        const directProp = contract.props?.[field];

        if (!mapping && !directProp) {
          missingMappings.push(field);
        }
      }

      if (missingMappings.length > 0) {
        result.errors.push(`Missing requirement field mappings: ${missingMappings.join(', ')}`);
        result.passed = false;
      }

      // 计算覆盖率
      const coverage = (requiredFields.length - missingMappings.length) / requiredFields.length;
      result.score = Math.round(coverage * 100);

      if (coverage < 1.0) {
        result.errors.push(`Requirement coverage ${result.score}% < 100%`);
        result.passed = false;
      }

    } catch (error) {
      result.errors.push(`Validation error: ${getErrorMessage(error)}`);
      result.passed = false;
    }

    return result;
  }

  /**
   * 运行所有验证
   */
  async runAllValidations(): Promise<{
    overall: boolean;
    results: ValidationResult[];
    summary: string;
  }> {
    console.log(`🔍 Running Phase Gate Validations for ${this.componentName}...`);

    const results: ValidationResult[] = [];

    // 运行各阶段验证
    results.push(await this.validateRequirementCoverage());
    results.push(await this.validatePhase2to3());
    results.push(await this.validatePhase3to4());
    results.push(await this.validatePhase4to5());

    // 生成摘要
    const overall = results.every(r => r.passed);
    const summary = this.generateSummary(results);

    // 保存结果
    const outputPath = path.join(this.componentName, 'phase-validation-report.json');
    fs.writeFileSync(outputPath, JSON.stringify({
      timestamp: new Date().toISOString(),
      component: this.componentName,
      overall,
      results,
      summary
    }, null, 2));

    console.log(summary);

    return { overall, results, summary };
  }

  /**
   * 生成验证摘要
   */
  private generateSummary(results: ValidationResult[]): string {
    const lines: string[] = [
      '\n' + '='.repeat(60),
      `Phase Gate Validation Report - ${this.componentName}`,
      '='.repeat(60)
    ];

    for (const result of results) {
      const status = result.passed ? '✅ PASS' : '❌ FAIL';
      const score = result.score !== undefined ? ` (Score: ${result.score}/100)` : '';
      lines.push(`\n${result.phase} - ${result.gate}: ${status}${score}`);

      if (result.errors.length > 0) {
        lines.push('  Errors:');
        result.errors.forEach(e => lines.push(`    ❌ ${e}`));
      }

      if (result.warnings.length > 0) {
        lines.push('  Warnings:');
        result.warnings.forEach(w => lines.push(`    ⚠️  ${w}`));
      }
    }

    const overall = results.every(r => r.passed);
    lines.push('\n' + '='.repeat(60));
    lines.push(`Overall Result: ${overall ? '✅ ALL GATES PASSED' : '❌ VALIDATION FAILED'}`);
    lines.push('='.repeat(60) + '\n');

    return lines.join('\n');
  }
}

// CLI执行
if (require.main === module) {
  const args = process.argv.slice(2);
  const componentName = args[0];
  const phase = args[1];

  if (!componentName) {
    console.error('Usage: ts-node phase-gate-validator.ts <ComponentName> [phase]');
    process.exit(1);
  }

  const validator = new PhaseGateValidator(componentName);

  (async () => {
    try {
      if (phase) {
        // 运行特定阶段验证
        let result: ValidationResult;
        switch (phase) {
          case '2-3':
            result = await validator.validatePhase2to3();
            break;
          case '3-4':
            result = await validator.validatePhase3to4();
            break;
          case '4-5':
            result = await validator.validatePhase4to5();
            break;
          case 'requirements':
            result = await validator.validateRequirementCoverage();
            break;
          default:
            console.error(`Unknown phase: ${phase}`);
            process.exit(1);
        }

        console.log(JSON.stringify(result, null, 2));
        process.exit(result.passed ? 0 : 1);
      } else {
        // 运行所有验证
        const { overall } = await validator.runAllValidations();
        process.exit(overall ? 0 : 1);
      }
    } catch (error) {
      console.error('Validation failed:', getErrorMessage(error));
      process.exit(1);
    }
  })();
}

export default PhaseGateValidator;